package top.csmcool.musicapi.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CacheWithExpiry<K, V> {

    private final Map<K, V> cache;
    private final Map<K, Long> expiryMap;
    private final long defaultExpiryTime; // 默认过期时间，单位：毫秒

    // 构造函数，传入默认的过期时间
    public CacheWithExpiry(long defaultExpiryTime) {
        this.cache = new ConcurrentHashMap<>();
        this.expiryMap = new ConcurrentHashMap<>();
        this.defaultExpiryTime = defaultExpiryTime;
    }

    // 存储缓存项
    public void put(K key, V value) {
        put(key, value, defaultExpiryTime);
    }

    // 存储缓存项，带有自定义过期时间
    public void put(K key, V value, long expiryTime) {
        long expiryTimestamp = System.currentTimeMillis() + expiryTime;
        cache.put(key, value);
        expiryMap.put(key, expiryTimestamp);
    }

    // 获取缓存项
    public V get(K key) {
        if (isExpired(key)) {
            remove(key); // 如果缓存过期，则移除该缓存项
            return null;
        }
        return cache.get(key);
    }

    // 检查缓存是否过期
    private boolean isExpired(K key) {
        Long expiryTimestamp = expiryMap.get(key);
        if (expiryTimestamp == null) {
            return true; // 如果没有找到过期时间，则认为过期
        }
        return System.currentTimeMillis() > expiryTimestamp;
    }

    // 移除缓存项
    public void remove(K key) {
        cache.remove(key);
        expiryMap.remove(key);
    }

    // 清空缓存
    public void clear() {
        cache.clear();
        expiryMap.clear();
    }

    // 打印缓存内容
    public void printCache() {
        System.out.println("Cache: " + cache);
    }

    public static void main(String[] args) throws InterruptedException {
        CacheWithExpiry<String, String> cache = new CacheWithExpiry<>(5000); // 默认5秒过期时间

        cache.put("key1", "value1");
        cache.put("key2", "value2", 2000); // 这个缓存项2秒后过期

        System.out.println("Before expiration:");
        cache.printCache();

        // 等待3秒钟，key2应该过期
        Thread.sleep(3000);

        System.out.println("After 3 seconds:");
        cache.printCache(); // key2应该被移除

        // 再等2秒钟，key1也过期
        Thread.sleep(2000);

        System.out.println("After 5 seconds:");
        cache.printCache(); // key1也应该被移除
    }
}
